<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2019/1/15
 * Time: 15:22
 */
namespace app\shop\controller;
use think\Db;
class Couponuse extends Base
{
    /**
     * 任务管理数据
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function homePage(){
        extract(input());
        $search = input('param.search/a');
        $page = input('param.page');
        if(!$page){
            $pages = 0;
        }else{
            $pages = $page-1;
        }

        $search = $this->search($search, $page);
        //搜索条件
        $map = [];
        //任务名称
        if($search[0] != " "){
            $map['coupon_name|mc_code|u.user_phone'] = ['like',"%" . $search[0] . "%"];
        }
        $map['mc_status'] = 2;
        $map['mc_s_id'] = session('shop_id');
        //1、列表
        $field = 'mc_use_time,coupon_name,coupon_image,mc_ercode,mc_code,mc_send';
        $field .= ',u.user_id,u.user_username,u.user_phone,u2.user_id user_id2,u2.user_username user_username2,u2.user_phone user_phone2';
        $data = Db::table('up_my_shop_coupon')->alias('c')
            ->join('up_shop_coupon sc','c.mc_coupon_id=sc.coupon_id','LEFT')
            ->join('up_u_user u','c.mc_user_id=u.user_id','LEFT')
            ->join('up_u_user u2','c.mc_send_user_id=u2.user_id','LEFT')
            ->where($map)
            ->order('mc_use_time DESC')
            ->field($field)
            ->paginate(25);
        return $this->fetch ('couponuse/home_page',['data'=>$data,'pages'=>$pages,'search'=>$search]);
    }


    /**
     * 获取当前商户的审核状态
     * @return \think\response\Json
     */
    public function hexiao()
    {
        extract(input());
        $today = date('Y-m-d H:i:s');
        $where = [
            'mc_s_id' => session('shop_id'),
            'mc_code' => $code,
        ];
        $can = Db::table('up_my_shop_coupon')->where($where)->find();
        if($can){
            if($can['mc_status'] != 1){
                return json(['status'=>0,'msg'=>'此码已经使用或者过期了']);
            }
            if($can['mc_send'] == 2 && $can['mc_send_status'] != 3){
                return json(['status'=>0,'msg'=>'此码还未被领取']);
            }
            $res = Db::table('up_my_shop_coupon')->where($where)->update([
                'mc_status' => 2,
                'mc_use_time' => $today,
            ]);
            Db::table('up_shop_coupon')->where('coupon_id',$can['mc_coupon_id'])->setInc('coupon_use_num');
            if($res){
                return json(['status'=>200,'msg'=>'核销成功']);
            }else{
                return json(['status'=>0,'msg'=>'核销失败']);
            }
        }else{
            return json(['status'=>0,'msg'=>'卡券不存在']);
        }
    }
}